package com.seven.netty.protocol.handler;

import com.seven.netty.protocol.bean.Head;
import com.seven.netty.protocol.bean.Message;
import com.seven.netty.protocol.constants.NettyConstant;
import com.seven.netty.protocol.enums.MessageTypeEnum;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * @author chendongdong
 * @description 心跳处理
 * @since 2024/3/6 10:53
 */
@Slf4j
public class ServerHeartBeatHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ChannelPipeline pipeline = ctx.channel().pipeline();
        ChannelPipeline pipeline1 = ctx.pipeline();
        log.debug("heart beat handler pipeline is equals {} , channel is equals {}", pipeline == pipeline1, ctx.channel() == ctx.pipeline().channel());
        Message message = (Message) msg;
        if (msg != null && message.getHead().getMessageType() == MessageTypeEnum.HEARTBEAT_REQUEST.getType().byteValue()) {
            Head head = Head.builder()
                .headIndex(NettyConstant.HEAD_INDEX)
                .crcCode(NettyConstant.CRC_CODE)
                .version(NettyConstant.VERSION)
                .sessionId(NettyConstant.LOGIN_SESSION_ID)
                .messageType(MessageTypeEnum.HEARTBEAT_RESPONSE.getType().byteValue())
                .length(NettyConstant.HEAD_LENGTH).build();
            message.setHead(head);
            ctx.writeAndFlush(message);
            log.debug("服务端收到心跳并响应:{}", message);
            System.out.println("服务端收到心跳并响应:" + message);
        } else {
            ctx.fireChannelRead(msg);
        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        log.error("heart beat error ", cause);
        ctx.close();
    }

    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {

        if (evt instanceof IdleStateEvent) {
            IdleState state = ((IdleStateEvent) evt).state();
            if (state == IdleState.READER_IDLE) {
                log.debug("服务端心跳检测 长时间未收到数据，关闭连接");
                System.out.println("服务端心跳检测 长时间未收到数据，关闭连接");
                //关闭连接
                ctx.channel().close();
            }
        } else {
            super.userEventTriggered(ctx, evt);
        }
    }
}
